package com.forsir.android.mhfinance;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

import com.forsir.android.mhfinance.helper.DbAdapter;
import com.forsir.android.mhfinance.helper.ManageItemsActivity;
import com.forsir.android.mhfinance.storeObjects.Account;
import com.forsir.android.mhfinance.storeObjects.AccountsList;
import com.forsir.android.mhfinance.storeObjects.IStorable;
import com.forsir.android.mhfinance.storeObjects.Payment;
import com.forsir.android.mhfinance.storeObjects.Repeating;

public class SelectAccount extends ManageItemsActivity {
	public final static String REQUEST_ALL_ACCOUNTS = "all_accounts";
	public final static String RETURN_ACCOUNT_POSITION = "account_position";
	public final static String RETURN_SELECTED_ACCOUNT_ID = "selected_account_id";

	private ListView accountListView;
	// select account for report
	private boolean allAccounts = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.select_account);
		setTheme(android.R.style.Widget_ListView_Menu);

		accountListView = (ListView) findViewById(R.id.select_account);

		if (savedInstanceState != null) {
			allAccounts = savedInstanceState.getBoolean(REQUEST_ALL_ACCOUNTS, false);
		} else {
			final Bundle extras = getIntent().getExtras();
			if (extras != null) {
				allAccounts = extras.getBoolean(REQUEST_ALL_ACCOUNTS, false);
			}
		}

		fillData();

		accountListView.setOnItemClickListener(accountListClickListener);
		if (!allAccounts) {
			accountListView.setOnItemLongClickListener(accountListLongClickListener);
		}
		registerForContextMenu(accountListView);

		if (AccountsList.getAccounts().size() == 0) {
			addNewItem(new Account());
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		final MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_account, menu);
		// onContextItemSelected is in ManageItemsActivity
	}

	private void fillData() {
		Account lastAccount = new Account(-1);
		boolean onlyIfEmpty = false;

		if (allAccounts) {
			lastAccount.setName(getString(R.string.all_accounts));
		} else {
			lastAccount.setName(getString(R.string.menu_account_new));

			if (mAddNewType.contentEquals("ever")) {
				onlyIfEmpty = false;
			} else if (mAddNewType.contentEquals("empty")) {
				onlyIfEmpty = true;
			} else if (mAddNewType.contentEquals("never")) {
				lastAccount = null;
				onlyIfEmpty = false;
			}
		}

		final SimpleAdapter categories = new SimpleAdapter(this, AccountsList.getGroup(lastAccount, onlyIfEmpty), android.R.layout.simple_expandable_list_item_2,
		        new String[] { "name" }, new int[] { android.R.id.text1 });

		accountListView.setAdapter(categories);
	}

	private final OnItemClickListener accountListClickListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			final Intent data = new Intent();
			final Account account = AccountsList.getAccount(position);

			if (account == null) {
				if (allAccounts) {
					SelectAccount.this.setResult(Activity.RESULT_OK, data);
					SelectAccount.this.finish();
					return;
				}
				addNewItem(new Account());
				return;
			}

			data.putExtra(SelectAccount.RETURN_SELECTED_ACCOUNT_ID, AccountsList.getAccount(position).getId());
			data.putExtra(SelectAccount.RETURN_ACCOUNT_POSITION, position);

			SelectAccount.this.setResult(Activity.RESULT_OK, data);
			// Close this Activity
			SelectAccount.this.finish();
		}
	};

	private final OnItemLongClickListener accountListLongClickListener = new OnItemLongClickListener() {
		public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
			if (AccountsList.getAccount(position) == null) { // clicked on Add new
				return true; // do nothing
			}
			return false;
		}
	};

	@Override
	protected void processAddNewItem(String name) {
		final Account account = new Account();
		account.setName(name);
		if (mDbHelper.createEntry(account) > 0) {
			Toast.makeText(this, String.format(getString(R.string.account_was_created), account.getName()), Toast.LENGTH_LONG).show();
		} else {
			Toast.makeText(this, getString(R.string.error_database_error), Toast.LENGTH_LONG).show();
		}

		AccountsList.loadAll(mDbHelper);
		fillData();
	};

	@Override
	protected void processDeleteItem(IStorable item) {
		if (item.getClass() == Account.class) {
			final Account account = (Account) item;
			// delete all account's payments
			mDbHelper.deleteEntries(new Payment(), DbAdapter.PAYMENT_ACCOUNT + "=" + account.getId());
			if (mDbHelper.deleteEntry(item)) {
				Toast.makeText(this, String.format(getString(R.string.account_was_deleted), account.getName()), Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(this, getString(R.string.error_database_error), Toast.LENGTH_LONG).show();
			}

			Repeating.deleteUnused(mDbHelper);
			AccountsList.loadAll(mDbHelper);
			fillData();
		}
	}

	@Override
	protected void processEditItem(IStorable item, String name) {
		if (item.getClass() == Account.class) {
			final Account account = (Account) item;
			account.setName(name);
			if (mDbHelper.updateEntry(account)) {
				Toast.makeText(this, String.format(getString(R.string.account_was_changed), account.getName()), Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(this, getString(R.string.error_database_error), Toast.LENGTH_LONG).show();
			}

			AccountsList.loadAll(mDbHelper);
			fillData();
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putBoolean(REQUEST_ALL_ACCOUNTS, allAccounts);
	}
}
